//
//  YXAouthViewController.swift
//  SinaWeiBo
//
//  Created by Vergil on 2017/6/5.
//  Copyright © 2017年 Vergil. All rights reserved.
//

import UIKit
import SVProgressHUD

class YXAouthViewController: UIViewController {
    
    lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        loadRequest()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

}


// MARK: - 设置UI
extension YXAouthViewController {
    
    fileprivate func setupUI() {
        
        view = webView
        webView.delegate = self
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        title = "登录新浪微博"
        //返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back))
        //自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        
    }
    
    //MARK: - 监听方法
    //返回
    @objc private func back() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //自动填充
    @objc private func autoFill() {
        //js代码
        let js = "document.getElementById('userId').value = '13961693614';" + "document.getElementById('passwd').value = 'Yang1993xi'"
        
        //执行js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
    
}

// MARK: - 加载请求
extension YXAouthViewController {
    
    fileprivate func loadRequest() {
        
        //1>url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)"
        //2>request
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url)
        //3>加载授权请求
        webView.loadRequest(request)
        
    }
    
}

// MARK: - UIWebViewDelegate
extension YXAouthViewController:UIWebViewDelegate {
    
    fileprivate func closeAndBack() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webview
    ///   - request: 请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否成功
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //如果请求地址头包含我们提供的回调地址,就继续,否则直接请求
        if request.url?.absoluteString.hasPrefix(WBRedirect_uri) == false{
            return true
        }
        //从回调地址的查询字段中查询code,如果有授权成功,如果没有,授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            
            SVProgressHUD.showInfo(withStatus: "授权失败")
            return false
            
        }
        
        //获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码 - \(code)")
        YXNetWork.Manager.loadAccessToken(code: code) { (isSuccess) in
            
            if isSuccess {
                
                SVProgressHUD.showInfo(withStatus: "授权成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserSuccessLoginNotification), object: nil)
                
                self.closeAndBack()
                
            } else {
                SVProgressHUD.showInfo(withStatus: "授权失败")
            }
            
        }
        
        return false
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
}
